package com.zion.tencent_dnspod_api.service;

import cn.hutool.json.JSONUtil;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.dnspod.v20210323.DnspodClient;
import com.tencentcloudapi.dnspod.v20210323.models.*;
import com.zion.tencent_dnspod_api.config.TencentConfig;
import com.zion.tencent_dnspod_api.entity.vo.DescribeDomainListVo;
import com.zion.tencent_dnspod_api.entity.vo.DescribeRecordListVo;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * DNSPod域名解析服务
 *
 * @Author ZionChen
 * @Date 2024/1/1 20:19
 * @PackageName:com.zion.dnspod_update.service
 * @ClassName: DnsPodService
 * @Description: TODO
 * @Version 1.0
 */
@Service
@Slf4j
public class DnsPodServiceImpl {

    @Resource
    private DnspodClient dnspodClient;

    @Resource
    private HostServiceImpl hostService;

    /***
     * 获取DNS域名配置列表
     * @return
     */
    public DescribeDomainListVo getDomainNameList() {
        log.info("调用腾讯第三方API查询域名列表");
        try {

            // 实例化一个请求对象,每个接口都会对应一个request对象
            DescribeDomainListRequest req = new DescribeDomainListRequest();

            // 返回的resp是一个DescribeDomainListResponse的实例，与请求对象对应
            DescribeDomainListResponse resp = dnspodClient.DescribeDomainList(req);
            // 输出json格式的字符串回包
            String resultEntity = DescribeDomainListResponse.toJsonString(resp);
            log.info("调用API返回的结果={}", resultEntity);
            DescribeDomainListVo resultBean = JSONUtil.toBean(resultEntity, DescribeDomainListVo.class);
            return resultBean;
        } catch (TencentCloudSDKException e) {
            log.error("调用API失败,code={}，请检查异常信息={}", e.getErrorCode(), e.getMessage());
            return null;
        }

    }

    /**
     * 获取域名的解析记录列表
     *
     * @return
     */
    public DescribeRecordListVo getDomainNameResolutionRecordList(DescribeRecordListRequest params) {
        try {
            // 返回的resp是一个DescribeRecordListResponse的实例，与请求对象对应
            DescribeRecordListResponse resp = dnspodClient.DescribeRecordList(params);
            // 输出json格式的字符串回包
            log.info("查询结果={}", DescribeRecordListResponse.toJsonString(resp));
            return JSONUtil.toBean(DescribeRecordListResponse.toJsonString(resp), DescribeRecordListVo.class);

        } catch (TencentCloudSDKException e) {
            log.error("查询域名解析记录列表失败，错误代码={},具体异常信息={}", e.getErrorCode(), e.getMessage());
            return null;
        }
    }


    /**
     * 批量修改IP记录
     *
     * @return 返回修改后的数据对象
     */
    public ModifyRecordBatchResponse ModifyRecordBatch(ModifyRecordBatchRequest request) {
        try {
            return dnspodClient.ModifyRecordBatch(request);
        } catch (TencentCloudSDKException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 根据域名，更新DNS服务
     *
     * @param domain 域名
     * @return 更新后的数据提醒
     */
    public DescribeRecordListVo updateDns(String domain) throws TencentCloudSDKException {
        //region 设置获取域名解析条目ID
        DescribeRecordListRequest recordListRequest = new DescribeRecordListRequest();
        recordListRequest.setDomain(domain);
        recordListRequest.setRecordType("A");
        DescribeRecordListVo recordListVo = this.getDomainNameResolutionRecordList(recordListRequest);
        //endregion

        //region 获取公网IP
        boolean getIp = false;
        String publicAddress = "";
        for (int i = 0; i < 4; i++) {
            try {

                log.info("获取当前域名A类型解析数据={}", JSONUtil.toJsonStr(recordListVo));
                publicAddress = hostService.getPublicAddress();
                log.info("获取公网IP={}", publicAddress);
                getIp = true;
                break;
            } catch (Exception e) {
                log.error("获取公网IP失败，开始重试");
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException ex) {
                    throw new RuntimeException(ex);
                }
            }
        }
        if (!getIp) {
            throw new RuntimeException("获取公网IP失败");
        }
        //endregion


        //region 循环解析条目，更新IP ,value
        for (RecordListItem recordListItem : recordListVo.getRecordList()) {
            log.info("当前记录item={}",JSONUtil.toJsonStr(recordListItem));
            ModifyRecordRequest req = new ModifyRecordRequest();
            req.setRecordLine(recordListItem.getLine());
            req.setDomain(domain);
            req.setRecordType(recordListItem.getType());
            req.setRecordId(recordListItem.getRecordId());
            req.setValue(publicAddress);
            req.setTTL(recordListItem.getTTL());
            req.setSubDomain(recordListItem.getName());
            log.info("req={}",JSONUtil.toJsonStr(req));
            ModifyRecordResponse resp = dnspodClient.ModifyRecord(req);
            log.info("更新DNS记录成功，返回的更新数据={}", ModifyRecordResponse.toJsonString(resp));
        }
        //endregion
        recordListVo = this.getDomainNameResolutionRecordList(recordListRequest);
        log.info("所有记录更新完毕={}", JSONUtil.toJsonStr(recordListVo));
        return recordListVo;
    }
}
